
# coding:utf-8
__author__ = 'admin'

# python rcmd.py -e -b -c echo.bat -i 127.0.0.1 -p 2000

from socket import socket, AF_INET, SOCK_STREAM
import gvars
import sys
import getopt




def sendcmd(address, data):
    s = socket(AF_INET, SOCK_STREAM)
    s.connect(address)
    s.send(data)
    s.send('\n' + gvars.EOFSTR)
    rstr = ''
    while True:
        buf = s.recv(1024)
        if not buf:
            break
        rstr += bytes(buf)
        if rstr.endswith(gvars.EOFSTR):
            break
    s.close()
    return rstr


if __name__ == '__main__':
    opts, argvs = getopt.getopt(sys.argv[1:], 'hebc:i:p:')
    eflag = False
    bflag = False
    hflag = False
    cmdstr = ''
    ip = ''
    port = 2000
    for name, value in opts:
        if name == '-e':
            eflag = True

        if name == '-b':
            bflag = True

        if name == '-c':
            cflag = True
            cmdstr = value
        if name == '-i':
            ip = value

        if name == '-p':
            port = value

    if cmdstr == '' or cmdstr is None or ip == '' or ip is None or port is None or (not (eflag or bflag)):
        print 'ERROR Haoopened'
        print 'Usage : rcmd -i ip -p port [-e] [-b] -c cmdline'
        exit(1)

    content = 'cmdline='+cmdstr + '\n'
    if eflag:
        content += 'optype=execute\n'
    elif bflag:
        content += 'optype=basecmd\n'

    result = sendcmd((ip, int(port)), content)
    print result










